﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Entities;
using Business;
using DevComponents.DotNetBar;
namespace Presentation
{
    public partial class frmQuanLySach : DevComponents.DotNetBar.Office2007Form
    {
        
        DataTable dt = new DataTable();
        DataView dv = new DataView();
        bool save;
        private bool isFormClosing = false;
        // Contant for the close message
        private const int WM_CLOSE = 16;
        //override the WndProc msg to trap the WM_CLOSE message
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_CLOSE)
                isFormClosing = true;
            base.WndProc(ref m);
        }
        public frmQuanLySach()
        {
            InitializeComponent();
            dgvSach.AutoGenerateColumns = false;
            
            DataGridViewTextBoxColumn colMaSach = new DataGridViewTextBoxColumn();
            colMaSach.Name = "MaSach";
            colMaSach.DataPropertyName = "MaSach";
            colMaSach.Width = 50;
            colMaSach.HeaderText = "Mã sách";
            colMaSach.ReadOnly = true;
            DataGridViewTextBoxColumn colTenSach = new DataGridViewTextBoxColumn();
            colTenSach.Name = "TenSach";
            colTenSach.DataPropertyName = "TenSach";
            colTenSach.HeaderText = "Tên sách";
            colTenSach.Width = 200;

            DataTable dtTheLoai = TheLoaiService.GetTheLoaiTable();
            DataGridViewComboBoxColumn colTheLoai = new DataGridViewComboBoxColumn();
            colTheLoai.Name = "MaTheLoai";
            colTheLoai.DataSource = dtTheLoai;
            colTheLoai.DisplayMember = "TenTheLoai";
            colTheLoai.ValueMember = "MaTheLoai";
            colTheLoai.DataPropertyName = "MaTheLoai";
            colTheLoai.HeaderText = "Thể loại";
            colTheLoai.AutoComplete = true;

            //
            DataTable dtTacGia = TacGiaService.GetTacGiaDataTable();
            DataGridViewComboBoxColumn colTacGia = new DataGridViewComboBoxColumn();
            colTacGia.Name = "MaTacGia";
            colTacGia.DataSource = dtTacGia;
            colTacGia.DisplayMember = "TenTacGia";
            colTacGia.ValueMember = "MaTacGia";
            colTacGia.DataPropertyName = "MaTacGia";
            colTacGia.HeaderText = "Tác giả";
            colTacGia.Width = 150;
            //colTacGia.AutoComplete = true;
            


            DataGridViewTextBoxColumn colSoLuong = new DataGridViewTextBoxColumn();
            colSoLuong.Name = "SoLuong";
            colSoLuong.DataPropertyName = "SoLuong";
            colSoLuong.HeaderText = "Số lượng tồn";

            DataGridViewTextBoxColumn colDonGia = new DataGridViewTextBoxColumn();
            colDonGia.Name = "DonGia";
            colDonGia.DataPropertyName = "DonGia";
            colDonGia.HeaderText = "Đơn giá";

            dgvSach.Columns.Add(colMaSach);
            dgvSach.Columns.Add(colTenSach);
            dgvSach.Columns.Add(colTheLoai);
            dgvSach.Columns.Add(colTacGia);
            dgvSach.Columns.Add(colSoLuong);
            dgvSach.Columns.Add(colDonGia);
            
        }

        private void frmQuanLySach_Load(object sender, EventArgs e)
        {
            LoadGridView();
            save = false;
        }
        void LoadGridView()
        {
            dt = SachService.GetSachTable();         
            dt.TableName = "Sach";
            dt.AcceptChanges();
            dv.Table = dt;
            dgvSach.DataSource = dt;
            btnCapNhat.Enabled = true;
            dgvSach.ReadOnly = false;
            save = false;
            
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        
        private void dgvSach_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (e.Control.GetType() == typeof(DataGridViewComboBoxEditingControl))
            {
                DataGridViewComboBoxEditingControl cb = e.Control as DataGridViewComboBoxEditingControl;
                cb.DropDownStyle = ComboBoxStyle.DropDown;
                cb.AutoCompleteSource = AutoCompleteSource.ListItems;
                cb.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                
                cb.SelectedIndex = -1;
            }
        }

        private void dgvSach_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            MessageBoxEx.Show("Nhập liệu không đúng!", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {

            LoadGridView();
        }

        private void dgvSach_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            int maSach=int.Parse(e.Row.Cells["MaSach"].FormattedValue.ToString());
            if (!SachService.CheckDelete(maSach))
            {
                MessageBoxEx.Show("Không thể xóa sách này!", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                e.Cancel = true;
            }
            else if(maSach>SachService.GetCurrentID())
            {
                for (int i = e.Row.Index+1; i < dgvSach.RowCount; i++)
                {
                    dgvSach["MaSach", i].Value = maSach++;
                }
                save = true;
            }
        }

        private void dgvSach_UserAddedRow(object sender, DataGridViewRowEventArgs e)
        {
            int id = GetID();
            for (int i = e.Row.Index - 1; i < dgvSach.RowCount; i++)
            {
                dgvSach["MaSach", i].Value = id++;
            }
            save = true;
        }

        private int GetID()
        {
            dv.RowStateFilter = DataViewRowState.Added;
            DataTable dtThem = dv.ToTable();

            int id = -1;
            if (dtThem.Rows.Count == 0)
            {
                id = SachService.GetCurrentID();
                if (id == 1 && SachService.GetSachByMaSach(id) == null)
                    id = 0;
            }
            else
            {
                id = (int)dtThem.Rows[dtThem.Rows.Count - 1]["MaSach"];

            }
            return id + 1;
        }

        private bool RowValidate(int rowIndex)
        {
            
            if (rowIndex == dgvSach.Rows.Count-1)
                return true;
            DataGridViewRow row = dgvSach.Rows[rowIndex];
            if (row.Cells["TenSach"].FormattedValue.ToString() == "")
            {
                MessageBox.Show(row.Cells["TenSach"].Value.ToString());
                return false;
            }
            if (row.Cells[2].FormattedValue.ToString() == "")
            {
                MessageBox.Show("Tác giả");
                return false;
            }
            
            if (row.Cells["SoLuong"].FormattedValue.ToString() == "")
            {
                MessageBox.Show("số lượng");
                return false;
            }
            if (row.Cells["DonGia"].FormattedValue.ToString() == "")
            {
                MessageBox.Show("Đon giá");
                return false;
            }

            return true;
        }

        private void dgvSach_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (isFormClosing)
                return;
            if (e.RowIndex < dgvSach.RowCount-1)
            {
                for (int i = 0; i < dgvSach.Columns.Count; i++)
                {
                    if (dgvSach[i,e.RowIndex].Value.ToString() == "")
                    {
                        MessageBoxEx.Show("Không được bỏ trống!", "Lỗi!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        dgvSach.CurrentCell = dgvSach[i, e.RowIndex];
                        dgvSach.BeginEdit(true);
                        e.Cancel = true;
                        return;
                    }
                }
            }
        }

        private void btnCapNhat_Click(object sender, EventArgs e)
        {
            if(CapNhat())
                MessageBoxEx.Show("Đã cập nhật!", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Information);
            else
                MessageBoxEx.Show("Không thể cập nhật!", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        private void dgvSach_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (isFormClosing)
                return;
            if (e.RowIndex == dgvSach.Rows.Count - 1)
                return;
            DataGridViewCell cell = dgvSach[e.ColumnIndex, e.RowIndex];

            if (e.FormattedValue.ToString() == "")
            {

                MessageBoxEx.Show("Nhập liệu không đúng!", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                cell.Style.BackColor = Color.Red;
                cell.Style.ForeColor = Color.White;

                dgvSach.CurrentCell = cell;
                dgvSach.BeginEdit(true);
                e.Cancel = true;
                return;

            }

            if (dgvSach.Columns[e.ColumnIndex].Name == "SoLuong" || dgvSach.Columns[e.ColumnIndex].Name == "DonGia")
            {
                double x = -1;
                if (!double.TryParse(e.FormattedValue.ToString(), out x) || x < 0)
                {
                    MessageBoxEx.Show("Nhập liệu không đúng!", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    cell.Style.BackColor = Color.Red;
                    cell.Style.ForeColor = Color.White;
                    dgvSach.CurrentCell = cell;
                    dgvSach.BeginEdit(true);

                    e.Cancel = true;
                    return;
                }

            }


            cell.Style.BackColor = Color.White;
            cell.Style.ForeColor = Color.Black;
        }

        private bool CapNhat()
        {
            dv.RowStateFilter = DataViewRowState.Added;
            DataTable dtThem = dv.ToTable();

            dv.RowStateFilter = DataViewRowState.ModifiedCurrent;
            DataTable dtCapNhat = dv.ToTable();

            dv.RowStateFilter = DataViewRowState.Deleted;
            DataTable dtXoa = dv.ToTable();
            bool kq = false;
            List<SachDTO> listThem = new List<SachDTO>();
            for (int i = 0; i < dtThem.Rows.Count; i++)
            {

                string tenSach, maTacGia, maTheLoai, donGia, soLuong;
                maTheLoai = dtThem.Rows[i]["MaTheLoai"].ToString();
                donGia = dtThem.Rows[i]["DonGia"].ToString();
                soLuong = dtThem.Rows[i]["SoLuong"].ToString();
                tenSach = dtThem.Rows[i]["TenSach"].ToString();
                maTacGia = dtThem.Rows[i]["MaTacGia"].ToString();

                int i_MaTheLoai, i_MaTacGia, i_SoLuong;
                double d_DonGia;
                if (tenSach == "" || !int.TryParse(maTheLoai, out i_MaTheLoai)
                    || !int.TryParse(maTacGia, out i_MaTacGia)
                    || !int.TryParse(soLuong, out i_SoLuong)
                    || !double.TryParse(donGia, out d_DonGia)
                    )
                    return false;
                SachDTO s = new SachDTO();
                s.TinhTrang = 1;
                s.TenSach = tenSach;
                s.MaTacGia = i_MaTacGia;
                s.MaTheLoai = i_MaTheLoai;
                s.SoLuong = i_SoLuong;
                s.DonGia = d_DonGia;
                listThem.Add(s);
            }
            List<SachDTO> listCapNhat = new List<SachDTO>();
            for (int i = 0; i < dtCapNhat.Rows.Count; i++)
            {
                string tenSach, maTacGia, maTheLoai, donGia, soLuong;
                maTheLoai = dtCapNhat.Rows[i]["MaTheLoai"].ToString();
                donGia = dtCapNhat.Rows[i]["DonGia"].ToString();
                soLuong = dtCapNhat.Rows[i]["SoLuong"].ToString();
                tenSach = dtCapNhat.Rows[i]["TenSach"].ToString();
                maTacGia = dtCapNhat.Rows[i]["MaTacGia"].ToString();

                int i_MaTheLoai, i_MaTacGia, i_SoLuong;
                double d_DonGia;
                if (tenSach == "" || !int.TryParse(maTheLoai, out i_MaTheLoai)
                    || !int.TryParse(maTacGia, out i_MaTacGia)
                    || !int.TryParse(soLuong, out i_SoLuong)
                    || !double.TryParse(donGia, out d_DonGia)
                    )
                    return false;
                SachDTO s = new SachDTO();
                s.TinhTrang = 1;
                s.TenSach = tenSach;
                s.MaTacGia = i_MaTacGia;
                s.MaTheLoai = i_MaTheLoai;
                s.SoLuong = i_SoLuong;
                s.DonGia = d_DonGia;
                listCapNhat.Add(s);
            }
            for (int i = 0; i < dtXoa.Rows.Count; i++)
            {
                int maSach = (int)dtXoa.Rows[i]["MaSach"];
                SachService.SetDelete(maSach);//Set trạng thái sách ==0 --> sách bị xóa tạm
                kq = true;
            }

            foreach (SachDTO sach in listCapNhat)
                SachService.Update(sach);

            foreach (SachDTO sach in listThem)
                SachService.Insert(sach);

            save = false;            
            btnCapNhat.Enabled = false;
            dgvSach.ReadOnly = true;
            return true;
        }
        private void frmQuanLySach_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (save && btnCapNhat.Enabled == true)
            {
                DialogResult r = MessageBoxEx.Show("Bạn có muốn lưu lại các thông tin?", "Thông báo!", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                if (r == DialogResult.Cancel)
                {
                    e.Cancel = true;
                    isFormClosing = false;
                }
                else if (r == DialogResult.Yes)
                {
                    if (!CapNhat())
                    {
                        MessageBoxEx.Show("Không thể cập nhật!", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        e.Cancel = true;
                        isFormClosing = true;
                    }
                }
            }
        }

        private void dgvSach_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            save = true;
        }

        private void dgvSach_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
        {
            save = true;
        }
    }
}
